<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>侦听器的使用</title>
</head>
<body>
    <div id="app">
        <!-- 加的数字不能大于10 减的数  不能小于0 -->
        <button type="button" @click="add">+</button>
        <h3>{{num}}</h3>
        <button type="button" @click="reduce">-</button>
    </div>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.js"></script>
    <script type="text/javascript">
    var vm = new Vue({
        el:'#app',
        data:{
            num:0,
            glab:false
        },
        methods: {
            add(){
                if(this.glab === true){
                    return
                }  
                this.num++;           
            },
            reduce(){
                this.num--;
            }
        },
        /* 监听器 */
        // watch:{
        //     /* 监听num属性的数据变化  一但属性发生变化  就触发  newVal是新的值 oldVal是旧的值*/
        //     num(newVal,oldVal){
        //         console.log(newVal,oldVal);
        //         if(newVal<0){
        //             this.num = 0;
        //         }
        //         if(newVal>10){
        //             this.glab = true;
        //             this.num = 10;
        //             alert("库存不足！！！")
                    
        //         }
        //     }
        // }
    });
    console.log(vm)
    var unwatch = vm.$watch('num', function(newVal,oldVal){
        console.log('new:',newVal)
		console.log('old:',oldVal)
        if(newVal<0){
            this.num = 0;
        }
        if(newVal>10){
            this.glab = true;
            this.num = 10;
            alert("库存不足");
        }
            //回调unwatch
            unwatch()
        },{
            //设置的选项对象
            immediate:true
        }    
    )
    </script>
</body>
</html>